//
//  ContactCenterMapViewController.m
//  ExpressData
//
//  Created by user on 12/11/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "ContactCenterMapViewController.h"
#import "CalloutMapAnnotation.h"
#import "CalloutMapAnnotationView.h"
#import "BasicMapAnnotationView.h"
#import "AccessorizedCalloutMapAnnotationView.h"
#import "BasicMapAnnotation.h"
#import "ContactDetailViewController.h"


#define centerAustraliaLatitude -25.324167
#define centerAustraliaLongitude 135.087891


@implementation ContactCenterMapViewController

@synthesize map;
@synthesize myTableView;
@synthesize customAnnotation = _customAnnotation;
@synthesize selectedAnnotationView = _selectedAnnotationView;
@synthesize calloutAnnotation = _calloutAnnotation;
@synthesize normalAnnotation = _normalAnnotation;


NSMutableArray *branchName;
NSMutableArray *keyList;
NSIndexPath *lastIndexPath;
NSMutableArray *addressDetail;
/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        // Custom initialization
    }
    return self;
}
*/
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
	if (annotation == self.calloutAnnotation) {
		CalloutMapAnnotationView *calloutMapAnnotationView = (CalloutMapAnnotationView *)[self.map dequeueReusableAnnotationViewWithIdentifier:@"CalloutAnnotation"];
		if (!calloutMapAnnotationView) {
			calloutMapAnnotationView = [[[AccessorizedCalloutMapAnnotationView alloc] initWithAnnotation:annotation 
																						 reuseIdentifier:@"CalloutAnnotation"] autorelease];
			
			

			
			UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, 280, 20)];
			titleLabel.text = self.customAnnotation.title;
			titleLabel.textAlignment = UITextAlignmentLeft;
			titleLabel.font = [UIFont fontWithName:@"HelveticaNeue-Bold" size:13];
			titleLabel.textColor = [UIColor whiteColor];
			titleLabel.shadowColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:.7];
			titleLabel.shadowOffset = CGSizeMake(0, -1.0);
			titleLabel.backgroundColor = [UIColor clearColor];
			titleLabel.lineBreakMode = UILineBreakModeWordWrap;
			titleLabel.numberOfLines = 3;
			
			UILabel *subtitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, titleLabel.frame.size.height + 8, 280, 20)];
			subtitleLabel.text = self.customAnnotation.subtitle;
			subtitleLabel.textAlignment = UITextAlignmentLeft;
			subtitleLabel.font = [UIFont fontWithName:@"HelveticaNeue" size:11];
			subtitleLabel.textColor = [UIColor whiteColor];
			subtitleLabel.shadowColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:.7];
			subtitleLabel.shadowOffset = CGSizeMake(0, -1.0);
			subtitleLabel.backgroundColor = [UIColor clearColor];
			subtitleLabel.lineBreakMode = UILineBreakModeWordWrap;
			subtitleLabel.numberOfLines = 5;
			
			CGSize subtitleLabelSize = [self.customAnnotation.subtitle sizeWithFont: subtitleLabel.font constrainedToSize: CGSizeMake(235, 600) lineBreakMode: subtitleLabel.lineBreakMode];
			subtitleLabel.frame = CGRectMake(subtitleLabel.frame.origin.x, subtitleLabel.frame.origin.y, subtitleLabelSize.width, subtitleLabelSize.height);
			
			
			UIView *calloutView =  [[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, titleLabel.frame.size.height + subtitleLabel.frame.size.height+13)];

			[calloutView addSubview : titleLabel];
			[calloutView addSubview : subtitleLabel];
			[calloutMapAnnotationView.contentView addSubview:calloutView];
			calloutMapAnnotationView.contentHeight = calloutView.frame.size.height + 5;

		}
		calloutMapAnnotationView.parentAnnotationView = self.selectedAnnotationView;
		calloutMapAnnotationView.mapView = self.map;
		return calloutMapAnnotationView;
	}
	//else {
	else if (annotation == self.customAnnotation) {
		MKPinAnnotationView *annotationView = [[[BasicMapAnnotationView alloc] initWithAnnotation:annotation 
																				  reuseIdentifier:@"CustomAnnotation"] autorelease];
		annotationView.canShowCallout = NO;
		annotationView.pinColor = MKPinAnnotationColorGreen;
		return annotationView;

	//}
	} else if (annotation == self.normalAnnotation) {
		MKPinAnnotationView *annotationView = [[[BasicMapAnnotationView alloc] initWithAnnotation:annotation 
																				  reuseIdentifier:@"NormalAnnotation"] autorelease];
		annotationView.canShowCallout = YES;
		annotationView.pinColor = MKPinAnnotationColorPurple;
		return annotationView;
	} else {
		MKPinAnnotationView *annotationView = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation 
																			   reuseIdentifier:@"BehindCalloutAnnotation"] autorelease];
		annotationView.canShowCallout = YES;
		annotationView.pinColor = MKPinAnnotationColorRed;
		return annotationView;
		
		
	} 
	return nil;
}


- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view {
	if (self.calloutAnnotation == nil) {
		self.calloutAnnotation = [[CalloutMapAnnotation alloc] initWithLatitude:view.annotation.coordinate.latitude
																   andLongitude:view.annotation.coordinate.longitude];
	}
	else {
		self.calloutAnnotation.latitude = view.annotation.coordinate.latitude;
		self.calloutAnnotation.longitude = view.annotation.coordinate.longitude;
	}
	[self.map addAnnotation:self.calloutAnnotation];
	self.selectedAnnotationView = view;
	}


- (void)mapView:(MKMapView *)mapView didDeselectAnnotationView:(MKAnnotationView *)view {
	if (self.calloutAnnotation && 
		view.annotation == self.customAnnotation && 
		!((BasicMapAnnotationView *)view).preventSelectionChange) {
		[self.map removeAnnotation: self.calloutAnnotation];
	}
}


- (void)mapView:(MKMapView *)mapView 
 annotationView:(MKAnnotationView *)view 
calloutAccessoryControlTapped:(UIControl *)control {
	//UIAlertView * alert = [[[UIAlertView alloc] initWithTitle:@"Asynchrony Solutions" 
	//												  message:@"Callout Accessory Tapped" 
	//												 delegate:nil 
	//										cancelButtonTitle:@"OK" 
	//										otherButtonTitles:nil] autorelease];
	//[alert show];
	UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStyleBordered target:nil action:nil];
	self.navigationItem.backBarButtonItem = backButton;
	[backButton release];
	ContactDetailViewController *contactDetailViewController = [[ContactDetailViewController alloc] initWithNibName:@"ContactDetailViewController"  bundle:nil];
	contactDetailViewController.keyList = [keyList objectAtIndex:0];
	contactDetailViewController.addressDetail = [addressDetail objectAtIndex:0];
	[self.navigationController pushViewController:contactDetailViewController animated:YES];
	[contactDetailViewController release];
}



// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	

	addressDetail = [[NSMutableArray alloc] init];
	branchName = [[NSMutableArray alloc] init];
	keyList = [[NSMutableArray alloc] init];
	[keyList addObject:[[NSMutableArray alloc]
						initWithObjects:
						@"Branch Name",
						@"Address",
						@"PO Box",
						@"Telephone",
						@"Sales Orders Fax",
						@"Customer Service",
						@"Website",
						@"latitude",
						@"longitude",nil]];
	[addressDetail addObject:[[NSMutableDictionary alloc]
							  initWithObjectsAndKeys:
							  @"New South Wales (HQ)",@"Branch Name",
							  @"14A Baker Street Botany  NSW 2019",@"Address",
							  @"PO Box 357 Botany 1455",@"PO Box",
							  @"(02) 8336 5100",@"Telephone",
							  @"(02) 9666 1240",@"Sales Orders Fax",
							  @"(02) 8336 5858",@"Customer Service",	
							  @"https://www.expressdata.com.au",@"Website",
							  @"-33.945508",@"latitude",
							  @"151.212831",@"longitude",
							  nil]];
	[keyList addObject:[[NSMutableArray alloc]
						initWithObjects:
						@"Branch Name",
						@"Address",
						@"Telephone",
						@"Fax",
						@"latitude",
						@"longitude",nil]];
	[addressDetail addObject:[[NSMutableDictionary alloc]
							  initWithObjectsAndKeys:
							  @"Australian Capital Territory",@"Branch Name",
							  @"32-36 Townshend Street Phillip ACT 2606",@"Address",
							  @"(02) 6229 2300",@"Telephone",
							  @"(02) 6285 4370",@"Fax",
							  @"-35.352761",@"latitude",
							  @"149.088292",@"longitude",
							  nil]];
	[keyList addObject:[[NSMutableArray alloc]
						initWithObjects:
						@"Branch Name",
						@"Address",
						@"Telephone",
						@"Fax",
						@"latitude",
						@"longitude",nil]];	
	
	[addressDetail addObject:[[NSMutableDictionary alloc]
							  initWithObjectsAndKeys:
							  @"Queensland",@"Branch Name",
							  @"Ground Floor 139  Coronation Drive Milton QLD 4064",@"Address",
							  @"(07) 3292 1333",@"Telephone",
							  @"(02) 3292 1334",@"Fax",
							  @"-27.472062",@"latitude",
							  @"153.006535",@"longitude",
							  nil]];
	[keyList addObject:[[NSMutableArray alloc]
						initWithObjects:
						@"Branch Name",
						@"Address",
						@"Telephone",
						@"Fax",
						@"latitude",
						@"longitude",nil]];
	[addressDetail addObject:[[NSMutableDictionary alloc]
							  initWithObjectsAndKeys:
							  @"Victoria",@"Branch Name",								  
							  @"Level 2 99 Coventry Street South Melbourne VIC 3205",@"Address",
							  @"(03) 9278 7200",@"Telephone",
							  @"(02) 9699 2103",@"Fax",
							  @"-37.830285",@"latitude",
							  @"144.965919",@"longitude",
							  nil]];
	[keyList addObject:[[NSMutableArray alloc]
						initWithObjects:
						@"Branch Name",
						@"Address",
						@"Telephone",
						@"Fax",
						@"latitude",
						@"longitude",nil]];
	[addressDetail addObject:[[NSMutableDictionary alloc]
							  initWithObjectsAndKeys:
							  @"South Australia",@"Branch Name",
							  @"4th Floor 139 Frome St Adela ide SA 5000",@"Address",
							  @"(03) 8236 8236",@"Telephone",
							  @"(02) 8227 1833",@"Fax",
							  @"-34.925815",@"latitude",
							  @"138.608183",@"longitude",
							  nil]];
	[keyList addObject:[[NSMutableArray alloc]
						initWithObjects:
						@"Branch Name",
						@"Address",
						@"Telephone",
						@"Fax",
						@"latitude",
						@"longitude",nil]];
	[addressDetail addObject:[[NSMutableDictionary alloc]
							  initWithObjectsAndKeys:
							  @"Western Australia",@"Branch Name",
							  @"Level 7 19 Pier St Perth WA 6000",@"Address",
							  @"(08) 6210 6800",@"Telephone",
							  @"(02) 9225 6399",@"Fax",
							  @"-31.955599",@"latitude",
							  @"115.861693",@"longitude",
							  nil]];
    [super viewDidLoad];
		
	CLLocation *ExpressData = [[[CLLocation alloc] initWithLatitude:centerAustraliaLatitude longitude:centerAustraliaLongitude] autorelease];
	MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(ExpressData.coordinate, 2630000, 2600000);
	[self.map setZoomEnabled:YES];
	[self.map setRegion:region animated:TRUE];
	[self.map regionThatFits:region];
	[self.map removeAnnotations:self.map.annotations];
	[branchName removeAllObjects];


	lastIndexPath = nil;
	self.map.delegate = self;
	
	UIBarButtonItem *resetButton = [[UIBarButtonItem alloc] 
								initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh   
								target:self 
								action:@selector(viewDidLoad)];
	[self.navigationItem setRightBarButtonItem:resetButton];

	self.title = @"Contact Center";
	self.view.backgroundColor = [UIColor colorWithPatternImage: [UIImage imageNamed:@"background1.png"]];

	for (int i=0; i < [addressDetail count]; i++) {
		
		
		
		NSString *latitude = [[addressDetail objectAtIndex:i] objectForKey:@"latitude"];
		NSString *longitude = [[addressDetail objectAtIndex:i] objectForKey:@"longitude"]; 
		CLLocationCoordinate2D c;
		c.latitude = [latitude doubleValue];
		c.longitude = [longitude doubleValue];
		NSMutableString *subtitle = [[NSMutableString alloc] initWithString:@""];
		NSMutableString *pinTitle;

		for (int j=0; j < [[keyList objectAtIndex:i] count]; j++ ) {
			NSString *dictionaryKey =[[keyList objectAtIndex:i] objectAtIndex:j];
			if ([dictionaryKey isEqualToString:@"Branch Name"]){
				pinTitle = [[addressDetail objectAtIndex:i] objectForKey:@"Branch Name"];
				[branchName addObject: [[addressDetail objectAtIndex:i] objectForKey:@"Branch Name"]];
				continue;
			}	
			if ([dictionaryKey isEqualToString:@"latitude"] || [dictionaryKey isEqualToString:@"longitude"]) continue;
		
			
			[subtitle appendString: [NSString stringWithFormat: @"%@ - %@\n", dictionaryKey,[[addressDetail objectAtIndex:i] objectForKey:dictionaryKey]]];
		

		}
		//BasicMapAnnotation *myCustomAnnotation = [[[BasicMapAnnotation alloc] initWithLatitude:c.latitude andLongitude:c.longitude] autorelease];
		self.customAnnotation = [[[BasicMapAnnotation alloc] initWithLatitude:c.latitude andLongitude:c.longitude title:pinTitle subtitle:subtitle] autorelease];
		[self.map addAnnotation:self.customAnnotation];
		//BLAnnotation *businessListingAnnotation = [[BLAnnotation alloc] initWithCoordinate: c title: pinTitle subtitle:subtitle];
		
		//[self.map addAnnotation: businessListingAnnotation];
		
		
		// respond to an annotation being selected by centering the map to it's coordinates
		//[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(centerMapToAnnotation:) name:@"annotationSelected" object:nil];
		
	
		
		
	}

	myTableView.separatorColor = [UIColor orangeColor];
	UITableViewCell *aCell;
	for(aCell in [myTableView visibleCells]){
		aCell.accessoryType = UITableViewCellAccessoryNone;
	}	
	[aCell release];
		
 
}
- (IBAction)toggleToolBarChange:(id)sender  
{  
    UISegmentedControl *segControl = sender;  
	
    switch (segControl.selectedSegmentIndex)  
    {  
        case 0: // Map  
        {  
            [self.map setMapType:MKMapTypeStandard];  
            break;  
        }  
        case 1: // Satellite  
        {  
            [self.map setMapType:MKMapTypeSatellite];  
            break;  
        }  
        case 2: // Hybrid  
        {  
            [self.map setMapType:MKMapTypeHybrid];  
            break;  
        }  
    }  
}  

//-(void) centerMapToAnnotation:(NSNotification *)note
//{
//	// Type dispatching annotation object
//	BLPinAnnotation *annotation = (BLPinAnnotation *)[note object];
//
//	// animate the map to the pin's coordinates
//	[self.map setCenterCoordinate:annotation.annotation.coordinate animated: YES];
//}

- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views
{
//    //Here
//  //  [mapView selectAnnotation:[[mapView annotations] objectAtIndex:0] animated:YES];
//	
	MKAnnotationView *aV; 
	for (aV in views) {
		CGRect endFrame = aV.frame;
		
		aV.frame = CGRectMake(aV.frame.origin.x, aV.frame.origin.y - 230.0, aV.frame.size.width, aV.frame.size.height);
	
		[UIView beginAnimations:nil context:NULL];
		[UIView setAnimationDuration:1.45];
		[UIView setAnimationCurve:UIViewAnimationTransitionCurlDown];
		[aV setFrame:endFrame];
		[UIView commitAnimations];
		
	}
	
}

// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [branchName count];
}



// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
		
    }
	
	
	NSString *cellvalue = [branchName objectAtIndex:indexPath.row];
	[cell.textLabel setText:cellvalue];
	cell.textLabel.textColor = [UIColor blackColor];	
	cell.textLabel.font = [UIFont systemFontOfSize:14]; //Change this value to adjust size 		
	return cell;
	
	
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
	//cell.backgroundColor = [UIColor whiteColor];
	cell.accessoryType = UITableViewCellAccessoryNone;
}



- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
	// create the parent view that will hold header Label
	UIView* customView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, tableView.frame.size.width, 30.0)];
	
	// create the button object
	UILabel * headerLabel = [[UILabel alloc] initWithFrame:CGRectZero];
	headerLabel.backgroundColor = [UIColor blackColor];
	headerLabel.opaque = YES;
	headerLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
	headerLabel.textColor = [UIColor whiteColor];
	headerLabel.highlightedTextColor = [UIColor whiteColor];
	headerLabel.font = [UIFont boldSystemFontOfSize:14];
	headerLabel.frame = CGRectMake(0.0, 0.0, tableView.frame.size.width, 30.0);
	
	// If you want to align the header text as centered
	// headerLabel.frame = CGRectMake(150.0, 0.0, 300.0, 44.0);
	
	headerLabel.text = @"Choose Branch"; // i.e. array element
	[customView addSubview:headerLabel];
	
	return customView;
}

- (void)tableView:(UITableView *)tableView 
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	
	UITableViewCell *theNewlySelectedCell = [tableView cellForRowAtIndexPath:indexPath];
	theNewlySelectedCell.accessoryType = UITableViewCellAccessoryCheckmark;
	
	if ( lastIndexPath != nil && [indexPath row] != [lastIndexPath row] )
	{
		UITableViewCell *theNowUnselectedCell = [tableView cellForRowAtIndexPath:lastIndexPath];
		theNowUnselectedCell.accessoryType = UITableViewCellAccessoryNone;
	}
	
	lastIndexPath = indexPath;
	
		
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
	for (id<MKAnnotation> currentAnnotation in self.map.annotations) { 
		if ([currentAnnotation.title isEqualToString:[branchName objectAtIndex:indexPath.row]]) {
				[self.map selectAnnotation:currentAnnotation animated:YES];
			break;
			}	
	}
	
	CLLocation *ExpressData = [[[CLLocation alloc] initWithLatitude:[[[addressDetail objectAtIndex:indexPath.row] valueForKey:@"latitude"] floatValue]  longitude:[[[addressDetail objectAtIndex:indexPath.row] valueForKey:@"longitude"] floatValue]] autorelease];
	MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(ExpressData.coordinate, 3000, 3000);
	[self.map setRegion:region animated:TRUE];
	[self.map regionThatFits:region];


	
}

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return YES;
}


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	self.map = nil;
	self.customAnnotation = nil;
	
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
	map.delegate = nil;
	[map release];
	[myTableView release];

    [super dealloc];
}


@end
